package cn.weiyx.movie;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;

import cn.weiyx.feign.UserFeignClient;

@RestController
public class MovieController {
	
	private static final Logger LOGGER = LoggerFactory.getLogger(MovieController.class);
	
	@Autowired
	private LoadBalancerClient loadBalancerClient;
	
	@Autowired
	private DiscoveryClient discoveryClient;
	
	@Autowired
	private RestTemplate template;
	
	@Autowired
	private UserFeignClient userFeignClient;
	
	@HystrixCommand(fallbackMethod = "findByIdFallback")
	@RequestMapping("/users.get.{id}")
	public User findById(@PathVariable Long id){
		return userFeignClient.findById(id);
//		return template.getForObject("http://springcloud-user/" + id, User.class);
	}
	
	public User findByIdFallback(Long id){
		User user = new User();
		user.setId(-1L);
		user.setName("默认用户");
		return user;
	}
	
	/**
	 *  查询用户服务的信息并返回
	 */
	@RequestMapping("/user-instance")
	public List<ServiceInstance> showInfo(){
		return this.discoveryClient.getInstances("springcloud-user");
	}
	
	@RequestMapping("/log-instance")
	public void logInstance(){
		ServiceInstance serviceInstance = this.loadBalancerClient.choose("springcloud-user");
		MovieController.LOGGER.info("=====服务名称{}--{}：{}", serviceInstance.getServiceId(), serviceInstance.getHost(), serviceInstance.getPort());
	}
	
}
